﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography.Xml;
using System.Text;
using System.Threading.Tasks;
using System.Xml;

namespace WinCustomsService
{
    public class XmlHelper
    {
        /// <summary>
        ///xml4NT
        /// </summary>
        /// <param name="xmlStr"></param>
        public static string XmlDsigC14NTransform(string xmlStr)
        {
          
            XmlDocument signedInfoXml = new XmlDocument();
            signedInfoXml.LoadXml(xmlStr);
          
            XmlDsigC14NTransform xmlTransform = new XmlDsigC14NTransform();
            xmlTransform.LoadInput(signedInfoXml);
            MemoryStream memoryStream = (MemoryStream)xmlTransform.GetOutput();
            return System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
        }

        /// <summary>
        /// SHA1加密转64string 
        /// </summary>
        /// <param name="str"></param>
        /// <param name="encoding"></param>
        /// <returns></returns>
        public static string Sha1Signature(string str, Encoding encoding)
        {
            var buffer = encoding.GetBytes(str);
            var data = System.Security.Cryptography.SHA1.Create().ComputeHash(buffer);
            return Convert.ToBase64String(data);
        }

        /// <summary>
        /// xml 转string
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        public static string ConvertXmlToString(XmlDocument xmlDoc)
        {
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, null);
            writer.Formatting = Formatting.Indented;
            xmlDoc.Save(writer);
            StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
            stream.Position = 0;
            string xmlString = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            return xmlString;
        }

        /// <summary>
        /// xml 转string
        /// </summary>
        /// <param name="xmlDoc"></param>
        /// <returns></returns>
        public static string ConvertXmlToString(XmlNode xmlDoc)
        {
            MemoryStream stream = new MemoryStream();
            XmlTextWriter writer = new XmlTextWriter(stream, null);
            writer.Formatting = Formatting.Indented;
           
            StreamReader sr = new StreamReader(stream, System.Text.Encoding.UTF8);
            stream.Position = 0;
            string xmlString = sr.ReadToEnd();
            sr.Close();
            stream.Close();
            return xmlString;
        }

    }
}
